<?php

class HotelController extends CController
{
	public function init()
	{
		SearchBox::show();
		parent::init();
	}
	
	public function actionIndex()
	{
		$this->setPageTitle('Отели');
		
		$records = null;
		$count   = null;
		
		$cityId = ((isset($_GET['cityid']) && intval($_GET['cityid']) != 0) ? intval($_GET['cityid']) : 0); 
		
		if ($cityId > 0) {
			$records = Hotel::model()->addStarsHtml2title()->findAll('cityId=:cityId', array(':cityId' => $cityId));
		} else {
			$records = Hotel::model()->addStarsHtml2title()->findAll();
		}
		
		$count = count($records);
		
		$cities  = CActiveRecordData::getArray(
			City::model()->criteria('title', 'asc')->findAll(),
			array('id', 'title'), false
		);

		$HotelPhoto = new HotelPhoto();
		$photos = $HotelPhoto->getData();
		
		$this->render('list', array(
			'cities' => $cities,
			'cityId' => $cityId > 0 ? $cityId : 0,
			'entity' => 'hotel',
			'data'   => $records,
			'photos' => $photos,
			'count'  => $count,
			'detailedUrl' => '/hotel/detailed/id/' 
		));
	}
	
	public function actionDetailed()
	{
		$hotelId = intval($_GET['id']);
		
		if ($hotelId > 0) {
			$hotel = Hotel::model()->with(array('city', 'hotelPhotos'))->findByPk($hotelId);
			$hotelFeatures = Hotel2hotelFeature::model()->with(array('feature'))->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId));
			$roomFeatures  = Hotel2roomFeature::model()->with(array('feature'))->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId));
			$excursions    = Hotel2excursion::model()->with(array('excursionData'))->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId));
			$hotelPhotos   = HotelPhoto::model()->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId));
			
			$this->setPageTitle($hotel->title);
			
			$this->render('detailed', array(
				'hotel'  => $hotel,
				'hotelFeatures' => $hotelFeatures,
				'roomFeatures'  => $roomFeatures,
				'excursions'    => $excursions,
				'hotelPhotos'   => $hotel->getRelated('hotelPhotos'),
				'priceColumns'  => HotelDateGroup::model()->criteria()->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId)),
				'gridConfig'    => HotelRoomAndDates::getConfig()
			));
		}
	}
	
	public function actionPrices()
	{
		$hotelId = intval($_GET['id']);
		
		if ($hotelId > 0) {
			$this->render('prices', array(
				'hotel'   => Hotel::model()->findByPk($hotelId),
				'data'    => HotelRoomAndDates::getPricesWithDates($hotelId, 'title asc'),
				'columns' => HotelDateGroup::model()->criteria()->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId)),
			));
		}
	}
	
	public function actionIframeprises()
	{
		$hotelId = intval($_GET['id']);
		
		if ($hotelId > 0) {
			$this->renderPartial('pricesIframe', array(
				'hotel'   => Hotel::model()->findByPk($hotelId),
				'data'    => HotelRoomAndDates::getPricesWithDates($hotelId, 'title asc'),
				'columns' => HotelDateGroup::model()->criteria()->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId)),
				'gridConfig' => HotelRoomAndDates::getConfig()
			));
		}
	}
	
	public function actionSearch()
	{
		$this->setPageTitle('Отели');
		
		$records = null;
		$count   = null;
		
		if (!array_key_exists('searchWord', $_POST)) {
			$this->redirect('/');
			die();
		}
		
		$search = strval($_POST['searchWord']);
		$keywords = substr($search, 0, 64);
		$keywords = preg_replace("/[^\w\x7F-\xFF\s]/", ' ', $keywords);
		$keywords = trim(preg_replace("/\s(\S{1,2})\s/", ' ', $keywords));
		
		$Hotel = new Hotel();
		$foundObjs = $Hotel->searchHotels($keywords);
		$count = count($foundObjs);
		
		$hotelIds = array();
		foreach ($foundObjs as $fObj) {
			$hotelIds[] = $fObj['id'];
		}
		
		$HotelPhoto = new HotelPhoto();
		$photos = $HotelPhoto->getData($hotelIds);
		
		$count = count($foundObjs);
		
		$this->render('search', array(
			'entity' => 'hotel',
			'data'   => $foundObjs,
			'photos' => $photos,
			'count'  => $count,
			'searchWord'  => $_POST['searchWord'],
			'keywords'    => $keywords, 
			'detailedUrl' => '/hotel/detailed/id/' 
		));
	}
	
	public function actionAdvancedsearch()
	{
		$this->setPageTitle('Отели');
		
		$hotels = CActiveRecordData::getArray(Hotel::model()->criteria('title', 'asc')->findAll());
		$cities = CActiveRecordData::getArray(City::model()->criteria('title', 'asc')->findAll());
		
		$this->render('advancedsearch', array(
			'entity' => 'hotel',
			'data'   => $hotels,
			'cities' => $cities, 
			'detailedUrl' => '/hotel/detailed/id/' 
		));
	}
	
	public function actionIframesearch()
	{
		$this->renderPartial('searchGridIframe', array(
			'hotel'   => Hotel::model()->findByPk($hotelId),
			'data'    => HotelRoomAndDates::getPricesWithDates($hotelId, 'title asc'),
			'columns' => HotelDateGroup::model()->criteria()->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId)),
			'gridConfig' => HotelRoomAndDates::getConfig()
		));
	}
	
	public function actionAdvancedsearchact()
	{
		$options = array();
		
		$page  = $options['page']  = intval($_POST['page']); // get the requested page
		$limit = $options['limit'] = intval($_POST['rows']); // get how many rows we want to have into the grid
		$options['sidx']  = $_POST['sidx']; // get index row - i.e. user click to sort
		$options['sord']  = $_POST['sord']; // get the direction 
		
		$date1 = '';
		if (preg_match('/[0-9]?[0-9]-[0-9]?[0-9]-[0-9][0-9][0-9][0-9]/', $_GET['date1'])) {
			$date1 = date('Y-m-d', strtotime($_GET['date1']));
		} else {
			$date1 = date('Y-m-d');
		}
		
		$date2 = '';
		if (preg_match('/[0-9]?[0-9]-[0-9]?[0-9]-[0-9][0-9][0-9][0-9]/', $_GET['date2'])) {
			$date2 = date('Y-m-d', strtotime($_GET['date2']));
		} else {
			$date2 = date('Y-m-d', time() + 7 * 24 * 60 * 60);
		}
		
		$price1 = floatval(str_replace(',', '', $_GET['price1']));
		$price2 = floatval(str_replace(',', '', $_GET['price2']));
		$stars  = intval($_GET['stars']);
		
		$cityIds = array();
		if (array_key_exists('city', $_GET) && count($_GET['city']) > 0) {
			foreach ($_GET['city'] as $val) {
				$cityIds[] = intval($val);
			}
		}
		
		$hotelIds = array();
		if (array_key_exists('hotel', $_GET) && count($_GET['hotel']) > 0) {
			foreach ($_GET['hotel'] as $val) {
				$hotelIds[] = intval($val);
			}
		}
		
		$hotelTitle = strval($_GET['hotelsearch']);

		$Hotel = new Hotel();
		
		$findParams = array(
			'date1' => $date1,
			'date2' => $date2,
			'price1'=> $price1,
			'price2'=> $price2,
			'stars' => $stars,
			'cityIds' => $cityIds,
			'hotelIds'=> $hotelIds,
			'hotelTitle' => $hotelTitle
		);
		
		$findData  = $Hotel->getAdvancedSearchData($findParams, $options);
		$findCount = $Hotel->getAdvancedSearchCount($findParams);
		
		$count = intval($findCount[0]['c']);
		$totalPages = 0;
		
		if ($count > 0) {
			$totalPages = ceil($count / $options['limit']);
		} 
		
		if ($page > $totalPages) {
			$page = $totalPages; 
		}
		
		$start = $limit * $page - $limit;;
		
		$responce = new stdClass();
		$responce->page    = $page;
		$responce->total   = $totalPages;
		$responce->records = $count; 
		
		$i = 0;
		foreach ($findData as $row) {
			$responce->rows[$i]['id']   = $row['id'];
			$responce->rows[$i]['cell'] = array(
				$row['room'], $row['hotel'], $row['city'], $row['stars'], $row['dateStart'], $row['dateEnd'], $row['price']
			);
			$i++;
		}
		
		die(json_encode($responce));
	}
	
	public function actionOrder()
	{
		$hotelId = intval($_GET['id']);
		
		if ($hotelId > 0) {
			$hotel = Hotel::model()->findByPk($hotelId);
			
			$this->setPageTitle('Бронирование гостиницы: ' . $hotel->title);
			
			$this->render('order', array(
				'hotel'  => $hotel
			));
		}
	}
	
	public function actionOrderprocess()
	{
		$postData = $_POST;
		
		$hotel = Hotel::model()->findByPk(intval($postData['hotelId']));
		
		$order = new Order();
		$order->attributes = $postData;
		
		if ($order->save()) {
			$config = new CConfiguration('protected/config/order.php');
			$config = $config->toArray();
			
			$subject = str_replace('%hotelName%', $hotel->title, $config['mail']['title']);
	
			$message = "<html><head><title>{$subject}</title></head><body>"
					. ( (array_key_exists('name', $postData) && $postData['name'] != '')  ? "<strong>Имя:</strong>&nbsp;{$postData['name']}<br /><br />" : '')
					. ( (array_key_exists('surename', $postData) && $postData['surename'] != '') ? "<strong>Фамилия:</strong>&nbsp;{$postData['surename']}<br /><br />" : '')
					. ( (array_key_exists('phone', $postData) && $postData['phone'] != '') ? "<strong>Телефон:</strong>&nbsp;{$postData['phone']}<br /><br />" : '')
					. ( (array_key_exists('email', $postData) && $postData['email'] != '') ? "<strong>e-mail:</strong>&nbsp;{$postData['email']}<br /><br />" : '')
					. ( (array_key_exists('comment', $postData) && $postData['comment'] != '') ? "<strong>Комментарии:</strong><br />" . nl2br($postData['comment']) : '');
			
			foreach ($config['mail']['receivers'] as $k => $v) {
				if (array_key_exists('email', $v) && $v['email'] != '') {
					
					sendMimeMail(
						$config['mail']['from']['name'],
						$config['mail']['from']['email'],
						$v['name'],
						$v['email'],
						'UTF-8',
						'KOI8-R',
						$subject,
						$message
					);
				}
			}
		}
		
		die('done');
	}
}